# -*- coding: utf-8 -*-
import os
import os.path
import json
import uuid
import time
import random
import string
import hashlib
import urllib
import copy
from functools import partial
import logging
import pprint
from tornado import gen

from tornado.escape import json_encode, json_decode, url_escape

import tornado
import tornado.web
import tornado.escape
import tornado.websocket
import tornado.httpclient
import tornado.gen

from setting import settings
from setting import conn

from datetime import datetime

from urllib import urlencode


from base import WebRequest
from base import WebSocket


logger = logging.getLogger(__name__)

from nomagic.cache import get_user, get_users, update_user, get_doc, get_docs, update_doc

class map_c(WebRequest):
    @gen.coroutine
    def post(self):
        print "map"
        data = json.loads(self.request.body)
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_url    = "http://api.map.baidu.com/direction/v1"
        mode        = "driving"
        ak          = "tvUEN48fN4HxiZYU77LpbHVY0y7xNVUZ"
        origin      = data['origin']
        destination = data['destination']

        url = '%s?mode=%s&origin=%s&destination=%s&origin_region=%s&destination_region=%s&output=json&ak=%s&coord_type=gcj02&ret_coordtype=gcj02' % (http_url, mode, origin, destination, 'shanghai', 'shanghai', ak)
        print url
        response =  yield  http_client.fetch(url)
        lines = []

        data = json_decode(response.body)

        path = ""


        for item in data['result']['routes'][0]['steps']:
            path += item['path']


        points = []

        for item in path.split(";"):
            j = item.split(",")
            point = {"longitude": j[0][0:8] , "latitude": j[1][0:8]}
            points.append(point)


                
        self.finish({"points":points})


        

class map_g(WebRequest):
    @gen.coroutine
    def post(self):
        print "map"
        data = json.loads(self.request.body)
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_url    = "http://restapi.amap.com/v3/place/around"
        ak          = "tvUEN48fN4HxiZYU77LpbHVY0y7xNVUZ"
        location    = data['location']
        keywords    = data['keywords'] 

        url = '%s?key=473f4d01263671e3d5b1a86883bf6f26&location=%s&output=json&radius=10000&keywords=%s&extensions=all' % (http_url, str(location), str(keywords))
        print url
        response =  yield  http_client.fetch(url)

        data = json_decode(response.body)
        
        self.finish(data)

